package org.unisinos.gc.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.unisinos.gc.dao.SubAreaDAO;
import org.unisinos.gc.dao.UtilDAO;
import org.unisinos.gc.form.SubAreaForm;
import org.unisinos.gc.vo.SubArea;

public class AddSubAreaAction extends Action {
	
	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		ActionErrors errors = new ActionErrors();
		ActionForward forward = null;
		try {
			super.execute(mapping, form, request, response);
			
			SubAreaForm subareaForm = (SubAreaForm)form;
			if (StringUtils.isNumeric(subareaForm.getCodigo()) && StringUtils.isNotEmpty(subareaForm.getNome()) && StringUtils.isNumeric(subareaForm.getCodigoArea())) {
				SubArea subarea = subareaForm.toSubArea();
				subarea.setCodigo(UtilDAO.getNextCodigo("subarea", "codigo"));
				SubAreaDAO.addSubArea(subarea);
				forward = mapping.findForward("success");
			}else {
				errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("invalidEntry"));
			}
		}catch (Exception e) {
			e.printStackTrace();
			errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("systemError"));
		}

		if (!errors.isEmpty()) {
			super.saveErrors(request, errors);
			forward = mapping.findForward("error");
			request.setAttribute("mode", "new");
		}
		
		return forward;
	}

}
